// pages/appointment/appointment.js
var app = getApp();
Page({
  data: {
    doctor: {}, // 医生信息
    // 新增地址相关数据
	address: '', // 显示地址
	locationAddress: '', // 详细地址
	latitude: null, // 纬度
	longitude: null, // 经度
    selectedDate: '', // 选择的日期
    selectedTime: '', // 选择的时间
    selectedSlot: '', // 选择的时间段
    timeSlots: ['08:00-09:00', '09:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00', '17:00-18:00', '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00'],
    bookedSlots: [], // 已被预约的时间段
    timeConflict: false, // 时间冲突标志
    
    // 被服务人信息
    patientName: '',
    genderOptions: ['男', '女', '其他'],
    genderIndex: 0,
    age: '', // 新增年龄字段，
    
    // 联系人信息
    contactName: '',
    contactPhone: '',
	phoneValid:false,
    verifyCode: '',
    showVerifyCode: false,
    isCountingDown: false,
    countdown: 0,
    
    // 服务内容
    serviceContent: '',
    
    // 表单验证
    isFormValid: false,
    
    // 日期范围
    minDate: '',
    maxDate: '',
  },

  onLoad(options) {
    // 从URL参数获取医生信息
    const doctor = wx.getStorageSync("selectDoctor")
    this.setData({ doctor });
    
    // 设置日期范围
    const now = new Date();
    const minDate = this.formatDate(new Date(now.getFullYear(), now.getMonth(), now.getDate()-1));
	console.log('minDate',minDate)
    const maxDate = this.formatDate(new Date(now.getFullYear(), now.getMonth() + 3, now.getDate()));
    const self = this
    //todo 获取对应社区的办公时间以及医生可预约时间
    app.util.request({
    	url: 'Community/getTime',
    	data: {
    		community_id: doctor.hospital_id,
    		doctor_id:doctor.id
    	},
    	success(res) {
    		var data = res.data.data;  
			 self.setData({ timeSlots:data.time,bookedSlots:data.doctor_time });
    	}
    })
    this.setData({
      minDate,
      maxDate
    });
    
  },
// 打开地图选择位置
  openMapSelect() {
    wx.chooseLocation({
      success: (res) => {
        if (res.name && res.address) {
          this.setData({
            address: res.name,
            locationAddress: res.address,
            latitude: res.latitude,
            longitude: res.longitude
          });
          this.checkFormValidity();
        }
      },
      fail: (err) => {
        console.error('选择位置失败', err);
        wx.showToast({
          title: '选择位置失败',
          icon: 'none'
        });
      }
    });
  },
  // 格式化日期为YYYY-MM-DD
  formatDate(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
  },


  // 检查时间段是否可用
  isTimeDisabled(timeSlot) {
    const { selectedDate, bookedSlots } = this.data;
    if (!selectedDate) return false;
    
    return bookedSlots.some(slot => 
      slot.date === selectedDate && slot.time === timeSlot
    );
  },

  // 选择日期
  onDateChange(e) {
    this.setData({
      selectedDate: e.detail.value,
      selectedSlot: '',
      timeConflict: false
    });
  },

  // 选择时间
  onTimeChange(e) {
    this.setData({
      selectedTime: e.detail.value,
      selectedSlot: '',
      timeConflict: false
    });
  },

  // 选择时间段
  selectTimeSlot(e) {
    const timeSlot = e.currentTarget.dataset.time;
    if (this.isTimeDisabled(timeSlot)) {
      this.setData({ timeConflict: true });
      return;
    }
    
    this.setData({
      selectedSlot: timeSlot,
      timeConflict: false
    });
    this.checkFormValidity();
  },

  // 地址变更
  onAddressChange(e) {
    this.setData({ address: e.detail.value });
    this.checkFormValidity();
  },

  // 被服务人姓名变更
  onPatientNameChange(e) {
    this.setData({ patientName: e.detail.value });
    this.checkFormValidity();
  },

  // 性别选择
  onGenderChange(e) {
    this.setData({ genderIndex: e.detail.value });
    this.checkFormValidity();
  },

 // 年龄变更处理
 onAgeChange(e) {
   let age = e.detail.value;
   // 限制年龄范围1-120岁
   if (age > 120) age = 120;
   if (age < 1) age = '';
   
   this.setData({ age });
   this.checkFormValidity();
 },

  // 联系人姓名变更
  onContactNameChange(e) {
    this.setData({ contactName: e.detail.value });
    this.checkFormValidity();
  },

  // 手机号变更
  onPhoneChange(e) {
	this.setData({ 
	  contactPhone: e.detail.value,
	  phoneValid: this.validatePhoneNumber(e.detail.value) // 添加校验状态
	});
	this.checkFormValidity();
  },

  // 验证码变更
  // onVerifyCodeChange(e) {
  //   this.setData({ verifyCode: e.detail.value });
  //   this.checkFormValidity();
  // },

  // 服务内容变更
  onServiceContentChange(e) {
    this.setData({ serviceContent: e.detail.value });
    this.checkFormValidity();
  },

  // 发送验证码
  // sendVerifyCode() {
  //   const { contactPhone } = this.data;
  //   if (!/^1[3-9]\d{9}$/.test(contactPhone)) {
  //     wx.showToast({ title: '请输入正确的手机号', icon: 'none' });
  //     return;
  //   }
    
  //   // 模拟发送验证码
  //   wx.showLoading({ title: '发送中...' });
  //   setTimeout(() => {
  //     wx.hideLoading();
  //     wx.showToast({ title: '验证码已发送' });
  //     this.startCountdown();
  //     this.setData({ showVerifyCode: true });
  //   }, 1000);
  // },

  // 开始倒计时
  // startCountdown() {
  //   this.setData({
  //     isCountingDown: true,
  //     countdown: 60
  //   });
    
  //   const timer = setInterval(() => {
  //     if (this.data.countdown <= 1) {
  //       clearInterval(timer);
  //       this.setData({
  //         isCountingDown: false,
  //         countdown: 0
  //       });
  //     } else {
  //       this.setData({ countdown: this.data.countdown - 1 });
  //     }
  //   }, 1000);
  // },
// 校验手机号是否合法
  validatePhoneNumber(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  },
  // 检查表单是否有效（修改）
    checkFormValidity() {
      const { 
        address, 
        selectedDate, 
        selectedSlot, 
        patientName, 
        contactName, 
        contactPhone, 
		phoneValid,
        // verifyCode, 
        // showVerifyCode,
        latitude,
		age,
        longitude
      } = this.data;
      
      const isValid = (
        address && 
        latitude &&
        longitude &&
        selectedDate && 
		age &&
        selectedSlot && 
        patientName && 
        contactName && 
        contactPhone &&
		phoneValid
        // (!showVerifyCode || verifyCode)
      );
      
      this.setData({ isFormValid: isValid });
    },

  // 提交预约
  submitAppointment() {
	  console.log(this.data.isFormValid)
    if (!this.data.isFormValid) return;
    
    const { 
      doctor, 
		address,
		locationAddress,
		latitude,
		longitude,
		selectedDate, 
		selectedSlot, 
		patientName, 
		genderIndex, 
		genderOptions, 
		age,
		contactName, 
		contactPhone, 
		// verifyCode, 
		serviceContent 
    } = this.data;
    
    // 验证验证码（实际开发中应调用API验证）
    // if (this.data.showVerifyCode && !this.verifyCode) {
    //   wx.showToast({ title: '请输入验证码', icon: 'none' });
    //   return;
    // }
    
    // 构造预约数据（新增位置坐标）
        const appointment = {
          doctorId: doctor.id,
          doctorName: doctor.name,
          communityId: doctor.hospital_id,
          serviceType: '医护上门',
          addressInfo: {
            name: address,
            address: locationAddress,
            latitude,
            longitude
          },
          appointmentDate: selectedDate,
          timeSlot: selectedSlot,
          patientInfo: {
            name: patientName,
            gender: genderOptions[genderIndex],
			age: parseInt(age)
          },
          contactInfo: {
            name: contactName,
            phone: contactPhone,
            // verifyCode
          },
          serviceContent,
          price: doctor.price||0,
          status: 'pending'
        };
    
    wx.showLoading({ title: '提交中...' });
    let jsonData = JSON.stringify(appointment);
    // todo 提交医护上门申请API调用
	app.util.request({
		url: 'Community/appintment',
		data: jsonData,
		method:'POST',
		headers: {
			'Content-Type': 'application/json',
		},
		success(res) {
			console.log(res)
			if(res.data.code){
				wx.showToast({ title: '预约成功' });
				setTimeout(() => {
				  wx.navigateBack();
				}, 1500);
			}else{
				wx.showToast({ title: '预约失败请重试' });
			}
		}
	})
  }
});